<template>
  <div class="home-container">
    <!-- 清洁机器人 -->
    <CleanRobot
        v-model="robotPosition"
        @clean="handleClean"
        @settings="showSettings"
        @openDialog="dialogVisible = true"
    />

    <!-- 清理对话框 - 现在位于Home组件中 -->
    <el-dialog
        title="清理数据"
        v-model="dialogVisible"
        width="30%"
        :before-close="handleDialogClose"
        class="clean-dialog"
        :close-on-click-modal="false"
        :append-to-body="false"
    >
    <div class="clean-dialog-content">
      <!-- 输入要删除的数据库名称 -->
      <el-form-item label="数据库名称">
        <el-input
            v-model="databaseName"
            placeholder="输入要删除的数据库名称"
        ></el-input>
        <el-button
            type="primary"
            size="small"
            class="delete-single-btn"
            @click="deleteSingleDatabase"
            :disabled="!databaseName"
        >
          删除指定数据库
        </el-button>
      </el-form-item>

      <!-- 清除所有数据库 -->
      <el-button
          type="danger"
          class="clean-all-btn"
          @click="confirmCleanAllDatabases"
      >
        <el-icon class="mr-1"><Delete /></el-icon>清除所有数据库
      </el-button>

      <!-- 清除所有AI对话信息 -->
      <el-button
          type="warning"
          class="clean-ai-btn"
          @click="confirmCleanAllAiConversations"
      >
        <el-icon class="mr-1"><MessageBox /></el-icon>清除所有AI对话信息
      </el-button>
    </div>
    </el-dialog>

    <!-- 确认对话框 -->
    <el-dialog
        title="确认操作"
        v-model="confirmDialogVisible"
        width="30%"
        class="confirm-dialog"
        :close-on-click-modal="false"
        :append-to-body="false"
    >
    <p>{{ confirmMessage }}</p>
    <template #footer>
      <el-button @click="confirmDialogVisible = false">取消</el-button>
      <el-button type="danger" @click="executeConfirmedAction">确认</el-button>
    </template>
    </el-dialog>

    <el-container class="main-container">
      <!-- 顶部导航栏 -->
      <LayoutHeader />

      <el-container class="middle-container">
        <!-- 左侧边栏（可拖动调整宽度） -->
        <div class="left-sidebar-wrapper">
          <LayoutSidebar
              :style="{
              width: leftPanelWidth + 'px',
              transition: 'width 0.2s ease',
              background: '#fff',
              borderRight: '1px solid #e8e8e8'
            }"
          />
          <!-- 左侧可拖动分隔条 -->
          <div
              class="resizer left-resizer"
              @mousedown="startLeftResize"
              :style="{ left: leftPanelWidth + 'px' }"
          ></div>
        </div>

        <!-- 主内容区域 -->
        <el-main
            :style="{
            flex: '1',
            minWidth: '0',
            width: `calc(100% - ${leftPanelWidth}px - ${rightPanelWidth}px)`,
            transition: 'width 0.2s ease',
            background: '#f8f9fa'
          }"
        >
          <router-view/>
        </el-main>

        <!-- 右侧面板 -->
        <div class="right-panel-wrapper">
          <div
              class="resizer right-resizer"
              @mousedown="startRightResize"
              :style="{ right: rightPanelWidth + 'px' }"
          ></div>
          <LayoutRightPanel
              :style="{
              width: rightPanelWidth + 'px',
              transition: 'width 0.2s ease',
              background: '#fff',
              borderLeft: '1px solid #e8e8e8',
              boxShadow: '-2px 0 12px rgba(0, 0, 0, 0.05)'
            }"
          />
        </div>
      </el-container>
      <LayoutFooter />
    </el-container>
  </div>
</template>

<script setup lang="ts">
import LayoutHeader from '@/components/LayoutHeader.vue'
import LayoutSidebar from '@/components/LayoutSidebar.vue'
import LayoutFooter from '@/components/LayoutFooter.vue'
import LayoutRightPanel from '@/components/LayoutRightPanel.vue'
import CleanRobot from '@/components/CleanRobot.vue'
import { ref, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'


// 机器人位置
const robotPosition = ref({ x: 30, y: 80 })

// 对话框状态
const dialogVisible = ref(false)
const confirmDialogVisible = ref(false)
const confirmMessage = ref('')
const databaseName = ref('')
let currentAction = ref('')

// 处理清理相关方法
const handleClean = () => {
  console.log('触发清理操作')
}

const showSettings = () => {
  console.log('打开设置面板')
}

const handleDialogClose = () => {
  dialogVisible.value = false
  databaseName.value = ''
}

const deleteSingleDatabase = () => {
  if (!databaseName.value.trim()) {
    ElMessage.warning('请输入数据库名称')
    return
  }

  confirmMessage.value = `确定要删除数据库 "${databaseName.value}" 吗？此操作不可恢复。`
  currentAction.value = 'deleteSingle'
  confirmDialogVisible.value = true
}

const confirmCleanAllDatabases = () => {
  confirmMessage.value = '确定要清除所有数据库吗？此操作将删除所有数据，不可恢复。'
  currentAction.value = 'cleanAllDatabases'
  confirmDialogVisible.value = true
}

const confirmCleanAllAiConversations = () => {
  confirmMessage.value = '确定要清除所有AI对话信息吗？此操作不可恢复。'
  currentAction.value = 'cleanAllAiConversations'
  confirmDialogVisible.value = true
}

const executeConfirmedAction = () => {
  confirmDialogVisible.value = false
  dialogVisible.value = false

  switch (currentAction.value) {
    case 'deleteSingle':
      // 调用实际删除指定数据库的逻辑
      ElMessage.success(`数据库 "${databaseName.value}" 已删除`)
      break
    case 'cleanAllDatabases':
      // 调用实际清除所有数据库的逻辑
      ElMessage.success('所有数据库已清除')
      break
    case 'cleanAllAiConversations':
      // 调用实际清除所有AI对话的逻辑
      ElMessage.success('所有AI对话信息已清除')
      break
  }

  databaseName.value = ''
}

// 左右面板宽度
const leftPanelWidth = ref(220)
const rightPanelWidth = ref(360)

// 拖动状态管理
let isResizingLeft = false
let isResizingRight = false
let startX = 0

const startLeftResize = (e: MouseEvent) => {
  isResizingLeft = true
  startX = e.clientX
  document.addEventListener('mousemove', handleLeftResize)
  document.addEventListener('mouseup', stopLeftResize)
  document.body.style.cursor = 'col-resize'
  document.body.style.userSelect = 'none'
}

const handleLeftResize = (e: MouseEvent) => {
  if (!isResizingLeft) return
  const offsetX = e.clientX - startX
  const maxWidth = document.documentElement.clientWidth - rightPanelWidth.value - 300

  leftPanelWidth.value = Math.min(
      Math.max(30, leftPanelWidth.value + offsetX),
      maxWidth
  )
  startX = e.clientX
}

const stopLeftResize = () => {
  isResizingLeft = false
  document.removeEventListener('mousemove', handleLeftResize)
  document.removeEventListener('mouseup', stopLeftResize)
  document.body.style.cursor = ''
  document.body.style.userSelect = ''
}

const startRightResize = (e: MouseEvent) => {
  isResizingRight = true
  startX = e.clientX
  document.addEventListener('mousemove', handleRightResize)
  document.addEventListener('mouseup', stopRightResize)
  document.body.style.cursor = 'col-resize'
  document.body.style.userSelect = 'none'
}

const handleRightResize = (e: MouseEvent) => {
  if (!isResizingRight) return
  const offsetX = startX - e.clientX
  const maxWidth = document.documentElement.clientWidth - leftPanelWidth.value - 300

  rightPanelWidth.value = Math.min(
      Math.max(10, rightPanelWidth.value + offsetX),
      maxWidth
  )
  startX = e.clientX
}

const stopRightResize = () => {
  isResizingRight = false
  document.removeEventListener('mousemove', handleRightResize)
  document.removeEventListener('mouseup', stopRightResize)
  document.body.style.cursor = ''
  document.body.style.userSelect = ''
}

const handleWindowResize = () => {
  const maxTotalWidth = document.documentElement.clientWidth - 100
  const currentTotalWidth = leftPanelWidth.value + rightPanelWidth.value

  if (currentTotalWidth > maxTotalWidth) {
    const scale = maxTotalWidth / currentTotalWidth
    leftPanelWidth.value *= scale
    rightPanelWidth.value *= scale
  }
}

window.addEventListener('resize', handleWindowResize)

onBeforeUnmount(() => {
  document.removeEventListener('mousemove', handleLeftResize)
  document.removeEventListener('mouseup', stopLeftResize)
  document.removeEventListener('mousemove', handleRightResize)
  document.removeEventListener('mouseup', stopRightResize)
  window.removeEventListener('resize', handleWindowResize)
})
</script>

<style scoped>
.home-container {
  height: 100vh;
  background: #f8f9fa;
  position: relative; /* 关键：让对话框相对于Home容器定位 */
  z-index: 1;
}

.main-container {
  height: 100%;
  flex-direction: column;

  ::v-deep(.el-header) {
    background: #fff;
    box-shadow: 0 2px 8px #f0f1f2;
    padding: 0 20px;
    height: 60px;
    display: flex;
    align-items: center;
  }

  .middle-container {
    height: calc(100% - 48px);
    min-height: 300px;
    display: flex;
    flex: 1;
    overflow: hidden;
  }

  ::v-deep(.el-main) {
    padding: 24px;
    overflow-y: auto;
  }

  ::v-deep(.el-footer) {
    position: relative;
    z-index: 1;
    height: 48px;
    background: #f8f9fa;
    border-top: 1px solid #e8e8e8;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #999;
    font-size: 14px;
  }
}

.left-sidebar-wrapper {
  display: flex;
  height: 100%;
  position: relative;
}

.right-panel-wrapper {
  display: flex;
  flex-direction: row-reverse;
  height: 100%;
  position: relative;
}

.resizer {
  width: 6px;
  background: #e8e8e8;
  cursor: col-resize;
  position: absolute;
  z-index: 999;
  top: 0;
  bottom: 0;
  transition: background 0.2s;

  &:hover {
    background: #409eff;
  }
  &:active {
    background: #2b79bd;
  }
}

.left-resizer {
  margin-left: -3px;
}

.right-resizer {
  margin-right: -3px;
}

/* 对话框样式 - 确保在Home组件中正确显示 */
:deep(.clean-dialog), :deep(.confirm-dialog) {
  z-index: 3000 !important; /* 高于页面其他元素 */

  .el-dialog__wrapper {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 3000;
  }
}

.clean-dialog-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.delete-single-btn {
  margin-top: 8px;
}

.clean-all-btn, .clean-ai-btn {
  width: 100%;
  justify-content: center;
}
</style>
